<script setup>
import { ElMessageBox, ElMessage } from 'element-plus'
import { check_article_list, check_articleStatus_list, check_submit } from '@/api/reject/check.js';
import { register_batch_list, } from '@/api/reject/register.js';
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
});
const { proxy } = getCurrentInstance();

const articleStatus = ref([{ value: 1, label: '待审核' }, { value: 0, label: '已通过' }, { value: 2, label: '已驳回' }])
const loading = ref(false);
const totalV = ref(0);
const articleList = ref([
    { productsId: 1, objectAmount: "白手套", batchName: "第一批次", productsNum: 10, productsUnqualified: 5, objectAmount: 3, flag: 1 }, { productsId: 2, objectAmount: "裤子", batchName: "第二批次", productsNum: 10, productsUnqualified: 5, objectAmount: 3, flag: 2 }
]);
const articleBatch = ref([])
const queryFormRef = ref();
const ids = ref([]);
const items = ref([]);
const dialog = ref({
    title: "",
    visible: false,
});
const unShowColumn = ref(false)
const dialogCheckReason = ref(false)
const articleRecord = ref([]);
const checkDialogValue = ref({ rejectAdvice: '' })
const multipleTableRef = ref()//清多选

/** 查询 */
function handleQuery() {
    loading.value = true;
    check_article_list(queryParams.value)
        .then(({ rows, total }) => {
            articleList.value = rows;
            totalV.value = total;
        })
        .finally(() => {
            loading.value = false;
        });
}
// 获取报废记录状态
function getArticleStatusList() {
    check_articleStatus_list().then((res) => {
        articleStatus.value = res.rows

        // let labels = articleStatus.map(article => ({ label: article.title }));
    })
}

// 获取批次列表
function getBatchList() {
    register_batch_list().then((res) => {
        articleBatch.value = res.data.map(item => ({ label: item.name, value: item.id }));
    })
}
/** 重置查询 */
function resetQuery() {
    queryFormRef.value.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
}

/** 行checkbox 选中事件 */
function handleSelectionChange(selection) {
    ids.value = selection;
    // ids.value = selection.map((item) => ({ articleId: item.productsId, articleName: item.objectAmount }));
}

/** 打开表单弹窗 */
function checkSubmit(dataTemp, type) {

    if (type === 0) {

        if (Array.isArray(dataTemp)) {

            let arrTemp = []
            dataTemp.map((item) => {
                arrTemp.push(Object.assign({}, item, { flag: type }))
            })

            articleRecord.value = arrTemp
        } else {
            articleRecord.value.push(dataTemp)
            articleRecord.value.flag = type
        }

        ElMessageBox.confirm('确定同意报废么吗?', '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => { // 注意这里使用了 async  

            if (!Array.isArray(dataTemp)) {
                articleRecord.value[0].flag = articleRecord.value.flag
                delete articleRecord.value.flag

            }
            //     let arrTemp = []
            // articleRecord.map((item) => {
            //     arrTemp.push(Object.assign({}, item, { flag: type }))
            // })

            // articleRecord.value = arrTemp

            try {
                // 使用 Promise.all 等待所有异步操作完成  
                await Promise.all(articleRecord.value.map(item => check_submit(item)));

                // 所有操作都成功完成后，显示成功消息并执行其他操作  
                ElMessage.success("提交成功");
                articleRecord.value = []
                closeDialog();
                resetQuery();
            } catch (error) {
                // 如果有任何一个操作失败，这里会捕获到错误  
                ElMessage({
                    type: 'info', message: '提交失败'
                });
            } finally {
                // 无论成功还是失败，都会执行这里的代码  
                handleQuery();
                articleRecord.value = []
            }
        }).catch(() => {
            // 如果确认对话框被取消，这里的 catch 会被触发  
            // 但根据你的代码逻辑，你可能不需要这个 catch，因为所有逻辑都在 then 的 async 函数中处理了  
        });
    }

    // }
    else if (type === 2) {
        dialogCheckReason.value = true;
        // checkDialogValue.value = data;
        checkDialogValue.value.flag = type;
        articleRecord.value[0] = dataTemp


    } else {
        ElMessageBox.confirm('确定撤回吗?', '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        // .then(
        // async () => {
        //请求接口 删除数据
        //       let r = await check_submit({data:data,type:type})
        //       if (r.code === 200) {
        //           ElMessage({ type: 'success', message: '撤回成功' })
        //       } else {
        //           ElMessage({ type: 'info', message: r.data })
        //       }
        //   }
        // ).catch(() => {
        //       ElMessage({
        //           type: 'info', message: '撤回失败'
        //       })
        //   }).finally(() => {
        //       handleQuery()
        //   })
        // }
    }
}

const checkRefuse = async () => {
    // articleRecord.value[0].flag = checkDialogValue.value.flag
    // articleRecord.value[0].rejectAdvice = checkDialogValue.value.rejectAdvice

    let tempTemp = articleRecord.value[0]
    tempTemp.flag = checkDialogValue.value.flag
    tempTemp.rejectAdvice = checkDialogValue.value.rejectAdvice

    // ElMessageBox.confirm('确定驳回申请吗?', '温馨提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    // }).then(
    // .then(

    // async () => {
    dialogCheckReason.value = false
    // articleRecord.value.flag=type

    // articleRecord.value.objectName=articleRecord.value.productsName
    // delete articleRecord.value.productsName
    // 请求接口 提交数据
    let r = await check_submit(tempTemp)
    if (r.code === 200) {
        ElMessage({ type: 'success', message: '提交成功' })

        handleQuery()
        checkDialogValue.value = { rejectAdvice: '' }
        articleRecord.value = []
    } else {
        ElMessage({ type: 'info', message: r.data })
    }
    // }

    // ).catch(() => {
    //     ElMessage({
    //         type: 'info', message: '提交撤回或失败'
    //     })
    // }).finally(() => {
    //     handleQuery()
    //     checkDialogValue.value = { rejectAdvice: '' }
    //     articleRecord.value = []
    // })

}

/** 导出按钮操作 */
const exportExcelFn = async () => {
    proxy.download("/applyWaste/exportformanager", {
        ...queryParams.value,
    }, `apply_${new Date().getTime()}.xlsx`);

}

/** 关闭表单弹窗 */
function closeDialog() {
    dialogCheckReason.value = false;
    multipleTableRef.value.clearSelection()
    checkDialogValue.value = { rejectAdvice: '' }
    articleRecord.value = []
    // resetForm();
    ids.value = []
    items.value = []
}

// 计算属性，用于获取 status 对应的标签类型（可选，取决于你是否需要为标签设置不同的类型）  
const getStatusType = computed(() => {
    const typeMap = {
        1: 'info', // 例如：待审核为信息类型  
        0: 'success', // 已通过为成功类型  
        2: 'warning', // 已驳回为警告类型  
    };
    return (status) => typeMap[status] || 'default'; // 默认类型  
});

// 方法，用于根据 status 获取对应的 label  
function getStatusLabel(status) {
    return articleStatus.value.find((item) => item.value === status)?.label || '未知状态';
}


onMounted(() => {
    handleQuery();
    // getArticleStatusList();
    getBatchList()
});
</script>

<template>
      <el-card class="page-container">
    <!-- <div class="app-container">
        <div class="search-container">
            <el-card shadow="hover" class="elCard"> -->

                <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                    <el-form-item prop="objectName" label="用品名称">
                        <el-input v-model="queryParams.objectName" placeholder="用品名称" clearable
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="批次" prop="batchId">
                        <el-select v-model="queryParams.batchId">
                            <el-option v-for="(item, index) in articleBatch" :index="item.value" :key="index"
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="flag" label="报废处理状态">
                        <el-select v-model="queryParams.flag">
                            <el-option v-for="(item, index) in articleStatus" :index="item.value" :key="index"
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleQuery"><el-icon>
                                <Search />
                            </el-icon>搜索</el-button>
                        <el-button @click="resetQuery"><el-icon>
                                <Refresh />
                            </el-icon>重置</el-button>
                    </el-form-item>
                </el-form>
            <!-- </el-card>
        </div>
        <el-card shadow="never" class="table-container"> -->
            <!-- <template #header> -->
                <div  class="mb8">
                <el-button  type="primary" plain icon="Plus" :disabled="ids.length === 0" @click="checkSubmit(ids, 0)">批量同意</el-button>

                <!-- <el-button type="success" :disabled="ids.length === 0" @click="checkSubmit(ids, 3)"><el-icon>
                        <RefreshLeft />
                    </el-icon>批量撤回</el-button> -->
                <el-button type="warning" plain icon="Download"  @click="exportExcelFn">
                    导出</el-button>
                </div>
            <!-- </template> -->

            <el-table v-loading="loading" :data="articleList" highlight-current-row border stripe height="520"
                ref="multipleTableRef" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" :selectable="(row, index) => {
                    return row.flag !== 0
                }" />
                <el-table-column type="index" label="序号" align="center" width="55">
                    <template #default="scope">
                        <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="记录id" prop="id" min-width="100" v-if="unShowColumn" align="center"/>
                <el-table-column label="用品id" prop="productsId" min-width="100" v-if="unShowColumn" align="center"/>
                <el-table-column label="批次id" prop="batchId" min-width="100" v-if="unShowColumn" align="center"/>
                <el-table-column label="申请人" prop="applicant"   align="center"/>
                <el-table-column label="用品名称" prop="objectName"   align="center"/>
                <!-- <el-table-column label="所属批次" prop="batchName" min-width="100" /> -->
                <el-table-column label="所属批次" prop="batchId"   align="center">
                    <template #default="scope">
                        <template v-for="item, index in articleBatch">
                            <span v-if="item.value == scope.row.batchId">
                                {{ item.label }}
                            </span>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="用品库存数量" prop="productsNum"   align="center"/>
                <el-table-column label="用品待报废总数" prop="productsUnqualified"   align="center"/>
                <el-table-column label="申请报废数量" prop="objectAmount"   align="center"/>
                <el-table-column label="报废处理状态" prop="flag" align="center">
                    <template #default="scope">

                        <el-tag :type="getStatusType(scope.row.flag)">
                            {{ getStatusLabel(scope.row.flag) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="220" align="center">
                    <template #default="scope">
                        <el-button v-if="scope.row.flag !== 0" type="primary" size="small" link
                            @click="checkSubmit(scope.row, 0)"><el-icon>
                                <Check />
                            </el-icon>同意
                        </el-button>
                        <el-button v-if="scope.row.flag === 1" type="primary" size="small" link
                            @click="checkSubmit(scope.row, 2)"><el-icon>
                                <Close />
                            </el-icon>驳回
                        </el-button>
                        <el-button v-if="scope.row.flag === 0" type="primary" size="small" link>申请已处理，无法操作
                        </el-button>
                        <!-- <el-button v-if="scope.row.flag!==1" type="primary" size="small" link @click="checkSubmit(scope.row)"><el-icon>
                                <RefreshLeft />
                            </el-icon>撤回
                        </el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                :page-sizes="[10, 20, 30, 40]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="totalV" @size-change="handleQuery" @current-change="handleQuery" style="margin-top: 20px; justify-content: flex-end" />
        <!-- </el-card> -->

        <!-- 审核按钮弹窗 -->
        <el-dialog title="拒绝报废" v-model="dialogCheckReason">
            <el-form label-width="120px" :model="checkDialogValue">
                <el-form-item label-width="10px" prop="checkDialogValue">
                    <el-input type="textarea" placeholder="请输入拒绝报废的原因"
                        v-model="checkDialogValue.rejectAdvice"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="checkRefuse">确 定</el-button>
            </template>
        </el-dialog>
    </el-card>
    <!-- </div> -->
</template>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .mb8 {
    margin-bottom: 8px;
  }
}
.elCard {
    margin-bottom: 10px;
}

.el-card {
    --el-card-padding: 12px;
}

.el-pagination {
    margin-top: 10px;
    margin-left: 10px;
}
</style>